<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown 笔记长截图生成器 (最终完美版)</title>
    <!-- 引入 Marked.js 用于解析 Markdown -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- 引入 html2canvas.js 用于生成截图 -->
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <style>
        :root {
            --bg-color-light: #f7f8fa; --bg-color-dark: #1e1e1e;
            --text-color-light: #2c3e50; --text-color-dark: #e0e0e0;
            --border-color-light: #eaecef; --border-color-dark: #3a3a3a;
            --panel-bg-light: #ffffff; --panel-bg-dark: #2a2a2a;
            --accent-color: #3498db;
            --code-bg-light: #f6f8fa; --code-bg-dark: #161b22;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
            margin: 0; padding: 0; background-color: var(--bg-color-light); color: var(--text-color-light); transition: background-color 0.3s, color 0.3s; line-height: 1.7;
        }
        
        .dark-mode { background-color: var(--bg-color-dark); color: var(--text-color-dark); }
        .container { max-width: 1400px; margin: 0 auto; padding: 20px; }
        header { text-align: center; margin-bottom: 20px; border-bottom: 1px solid var(--border-color-light); padding-bottom: 20px; }
        .dark-mode header { border-bottom-color: var(--border-color-dark); }
        header p { color: #888; font-size: 0.9em; }
        .controls { display: flex; justify-content: center; align-items: center; gap: 20px; margin-bottom: 20px; flex-wrap: wrap; }
        .control-item { display: flex; align-items: center; gap: 8px; }
        .control-item label { font-size: 14px; color: #666; }
        .dark-mode .control-item label { color: #bbb; }
        .main-content { display: flex; gap: 20px; height: calc(100vh - 220px); }
        .editor-pane, .preview-pane { flex: 1; background-color: var(--panel-bg-light); border: 1px solid var(--border-color-light); border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; transition: background-color 0.3s, border-color 0.3s; }
        .dark-mode .editor-pane, .dark-mode .preview-pane { background-color: var(--panel-bg-dark); border-color: var(--border-color-dark); }
        .pane-header { padding: 10px 15px; font-weight: bold; background-color: #f1f1f1; border-bottom: 1px solid var(--border-color-light); }
        .dark-mode .pane-header { background-color: #333; border-bottom-color: var(--border-color-dark); }
        #markdown-input { width: 100%; height: 100%; padding: 15px; border: none; outline: none; font-family: "SF Mono", "Fira Code", monospace; font-size: 14px; resize: none; background-color: inherit; color: inherit; }
        
        #preview-output-wrapper { overflow: auto; height: 100%; text-align: center; padding: 20px 0; }
        
        /* 【修复】将 #preview-output 改为 .markdown-body 类选择器 */
        .markdown-body {
            display: inline-block; text-align: left;
            transition: width 0.3s ease-in-out;
            box-sizing: border-box;
            padding: 25px 35px;
            background-color: var(--panel-bg-light);
        }
        .dark-mode .markdown-body { background-color: var(--panel-bg-dark); }

        .btn, .select, .input-custom-width { padding: 10px; font-size: 16px; border: 1px solid transparent; border-radius: 5px; cursor: pointer; transition: background-color 0.2s; background-color: #7f8c8d; color: white; vertical-align: middle; }
        .select { padding-right: 20px; padding-left: 20px;}
        .input-custom-width {
            width: 80px;
            background-color: #ecf0f1;
            color: #333;
            border: 1px solid #bdc3c7;
            cursor: text;
        }
        .dark-mode .input-custom-width { background-color: #3a3a3a; color: #e0e0e0; border-color: #555;}
        
        #export-btn { background-color: var(--accent-color); font-weight: bold; }
        #export-btn:hover { background-color: #2980b9; }
        #export-btn:disabled { background-color: #bdc3c7; cursor: not-allowed; }
        #theme-toggle:hover, .select:hover { background-color: #6c7a7b; }
        
        /* 【修复】将所有 #preview-output 选择器改为 .markdown-body */
        .markdown-body h1, .markdown-body h2, .markdown-body h3 { border-bottom: 1px solid var(--border-color-light); padding-bottom: 0.3em; margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; }
        .dark-mode .markdown-body h1, .dark-mode .markdown-body h2, .dark-mode .markdown-body h3 { border-bottom-color: var(--border-color-dark); }
        .markdown-body code { font-family: "SF Mono", "Fira Code", monospace; background-color: var(--code-bg-light); color: #333; padding: 0.2em 0.4em; margin: 0; font-size: 85%; border-radius: 3px; }
        .dark-mode .markdown-body code { background-color: var(--code-bg-dark); color: #c9d1d9; }
        
        .markdown-body pre { 
            background-color: var(--code-bg-light); 
            padding: 16px; 
            overflow: visible; /* 必须设为 visible 才能配合换行 */
            font-size: 85%; 
            line-height: 1.45; 
            border-radius: 6px; 
            white-space: pre-wrap;     /* 允许保留格式的同时自动换行 */
            word-break: break-all;     /* 在任意字符间断行，确保长字符串也能换行 */
        }
        .dark-mode .markdown-body pre { background-color: var(--code-bg-dark); }
    </style>
</head>
<body>

    <div class="container">
        <header>
            <h1>Markdown 笔记长截图生成器</h1>
            <p>所见即所得！选择预设或输入自定义宽度，一键导出带精美边距的长截图。</p>
        </header>

        <div class="controls">
            <div class="control-item">
                <label for="width-selector">预览/截图宽度:</label>
                <select id="width-selector" class="select">
                    <option value="800" selected>手机 (800px)</option>
                    <option value="1024">平板 (1024px)</option>
                    <option value="1280">桌面 (1280px)</option>
                    <option value="custom">自定义…</option>
                </select>
                <input type="number" id="custom-width-input" class="input-custom-width" value="1600" min="400" style="display: none;">
            </div>
            <button id="export-btn" class="btn">导出长截图</button>
            <button id="theme-toggle" class="btn">切换到暗色模式</button>
        </div>

        <div class="main-content">
            <div class="editor-pane">
                <div class="pane-header">Markdown 输入</div>
                <textarea id="markdown-input" placeholder="请在这里粘贴你的 Markdown 笔记..."></textarea>
            </div>
            <div class="preview-pane">
                <div class="pane-header">实时预览 (宽度已同步)</div>
                <div id="preview-output-wrapper">
                    <!-- 【修复】增加 markdown-body 类 -->
                    <div id="preview-output" class="markdown-body"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const markdownInput = document.getElementById('markdown-input');
        const previewOutput = document.getElementById('preview-output');
        const exportBtn = document.getElementById('export-btn');
        const themeToggle = document.getElementById('theme-toggle');
        const widthSelector = document.getElementById('width-selector');
        const customWidthInput = document.getElementById('custom-width-input');

        const placeholderText = `
# 欢迎使用 Markdown 笔记生成器 (最终完美版)

这个版本带来了终极的灵活性和稳定性！

## 最终优化

- **智能代码换行**：超长的代码行再也不会被截断，会自动换行显示。
- **明确的宽度标签**：下拉菜单中的预设选项会明确标注其像素值。
- **自定义宽度**：选择“自定义…”即可输入任意宽度。
- **优雅边距**：导出的截图会自动添加漂亮的页边距。

---

**现在，您可以完全掌控您的分享样式了！**
        `;

        function renderMarkdown() {
            previewOutput.innerHTML = marked.parse(markdownInput.value);
        }

        function getCurrentWidth() {
            return (widthSelector.value === 'custom') 
                ? parseInt(customWidthInput.value, 10) || 1280 
                : parseInt(widthSelector.value, 10);
        }

        function syncPreviewWidth() {
            previewOutput.style.width = `${getCurrentWidth()}px`;
        }

        function handleWidthSelectionChange() {
            customWidthInput.style.display = (widthSelector.value === 'custom') ? 'inline-block' : 'none';
            syncPreviewWidth();
        }

        async function exportAsImage() {
            exportBtn.disabled = true;
            exportBtn.textContent = '正在生成中...';
            let screenshotWrapper = null;
            try {
                // 1. 获取当前预览区的背景色，作为“画框”的背景
                const finalBgColor = window.getComputedStyle(previewOutput).backgroundColor;

                // 2. 创建一个带页边距的“画框”（Wrapper）
                screenshotWrapper = document.createElement('div');
                screenshotWrapper.style.position = 'absolute';
                screenshotWrapper.style.top = '-9999px';
                screenshotWrapper.style.left = '-9999px';
                screenshotWrapper.style.backgroundColor = finalBgColor;
                screenshotWrapper.style.padding = '40px';
                screenshotWrapper.style.width = 'auto'; // 宽度由内容决定

                // 3. 【核心修复】完整克隆预览区，保证所有子元素和样式被继承
                const contentClone = previewOutput.cloneNode(true);
                // 确保克隆体宽度正确，且没有不必要的滚动条
                contentClone.style.width = `${getCurrentWidth()}px`;
                contentClone.style.height = 'auto';
                contentClone.style.overflow = 'visible';
                contentClone.style.display = 'block';

                // 4. 将克隆体放入画框，再将画框放入页面
                screenshotWrapper.appendChild(contentClone);
                document.body.appendChild(screenshotWrapper);

                // 5. 对整个“画框”进行截图
                const canvas = await html2canvas(screenshotWrapper, {
                    scale: 2,
                    useCORS: true,
                });

                // 6. 下载图片
                const link = document.createElement('a');
                link.href = canvas.toDataURL('image/png');
                const timestamp = new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "");
                link.download = `笔记分享_${timestamp}.png`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error('导出图片时发生错误:', error);
                alert('抱歉，生成截图失败！请检查控制台获取更多信息。');
            } finally {
                if (screenshotWrapper) {
                    document.body.removeChild(screenshotWrapper);
                }
                exportBtn.disabled = false;
                exportBtn.textContent = '导出长截图';
            }
        }

        function toggleTheme() {
            document.body.classList.toggle('dark-mode');
            const isDarkMode = document.body.classList.contains('dark-mode');
            themeToggle.textContent = isDarkMode ? '切换到亮色模式' : '切换到暗色模式';
            localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
        }

        function initializeTheme() {
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
                themeToggle.textContent = '切换到亮色模式';
            }
        }

        markdownInput.addEventListener('input', renderMarkdown);
        exportBtn.addEventListener('click', exportAsImage);
        themeToggle.addEventListener('click', toggleTheme);
        widthSelector.addEventListener('change', handleWidthSelectionChange);
        customWidthInput.addEventListener('input', syncPreviewWidth);

        document.addEventListener('DOMContentLoaded', () => {
            initializeTheme();
            markdownInput.value = placeholderText.trim();
            renderMarkdown();
            syncPreviewWidth();
        });
    </script>
    
</body>
</html>